'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  const { keyword } = event;
  
  if (!keyword) {
    return {
      code: 400,
      msg: '关键词不能为空'
    };
  }

  try {
    // 创建正则表达式对象，用于模糊匹配
    const regex = new db.RegExp({
      regexp: `.*${keyword}.*`,
      options: 'i'
    });

    // 构建查询条件，支持对 title、owner 和 address 字段的模糊搜索
    const query = db.collection('saigedata')
      .where(db.command.or(
        { title: regex },
        { owner: regex },
        { address: regex }
      ))
      .limit(5);

    const res = await query.get();

    return {
      code: 200,
      msg: '查询成功',
      data: res.data
    };
  } catch (e) {
    return {
      code: 500,
      msg: '查询失败',
      error: e.message
    };
  }
};